package com.lemon.components.ant.project.makers;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;

import com.lemon.components.ant.beans.ProjectInfo;
import com.lemon.components.ant.project.ProjectMaker;
import com.lemon.components.ant.project.beans.ColumnInfo;
import com.lemon.components.ant.project.beans.EnumInfo;
import com.lemon.components.ant.project.beans.TableInfo;
import com.lemon.components.ant.util.ConfigUtil;
import com.lemon.components.ant.util.PathUtil;
import com.lemon.components.ant.util.TemplateUtil;
import com.lemon.ui.codemaker.component.RecentlyFile;
import com.system.core.security.NameUtil;

public class MybatisGenerator {
	
	private static Pattern pattern = Pattern.compile("'.*'");
	private static PathUtil pathUtil;

	public static void build(String cmd,String dir) throws Exception {
		Process p = Runtime.getRuntime().exec("cmd /c "+cmd, null, new File(dir));
		BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream(),"gbk"), 1024);
		String tmp;
		while((tmp = br.readLine())!=null){
			System.out.println(tmp);
		}
		p.waitFor();
	}
	
	public static Map<String, List<String>> getEnums(List<ColumnInfo> columns) {
		Map<String, List<String>> enums = new HashMap<String, List<String>>();
		
		for(ColumnInfo columnInfo:columns) {
			if(columnInfo.getColumnType().indexOf("enum") >= 0) {
				Matcher m = pattern.matcher(columnInfo.getColumnType());
				if(m.find()) {
					List<String> list = new ArrayList<>();
					String[] tmp = m.group(0).replaceAll("'", "").split(",");
					boolean yesnoEnum = false;
					for(String s : tmp) {
						list.add(s);
						if(s.equals("YES")||s.equals("NO"))
							yesnoEnum = true;
					}
					if(tmp.length == 2 && yesnoEnum) {
						columnInfo.setYesnoEnum(yesnoEnum);
					} else {
						enums.put(columnInfo.getJavaCode(), list);
					}
				}
			}
		}
		
		return enums;
	}
	
	public static void make(String[] columnNameList) {
		ProjectInfo projectInfo = ConfigUtil.getInstance(RecentlyFile.configFilePath).getProjectInfo();
		pathUtil = PathUtil.getInstance(projectInfo);
//		MysqlLocalTool.createdb(ConfigUtil.getProjectInfoNoTable());
//		MysqlLocalTool.importSQL(ConfigUtil.getProjectInfoNoTable());
		makeEnums(projectInfo);
		
		if(columnNameList != null) {
			List<TableInfo> newTablelist = projectInfo.getTables().stream().filter(new Predicate<TableInfo>() {
				
				@Override
				public boolean test(TableInfo t) {
					for(String column:columnNameList) {
						if(column.equalsIgnoreCase(t.getTableName()))
							return true;
					}
					return false;
				}
			}).collect(Collectors.toList());
			if(!newTablelist.isEmpty())
				projectInfo.setTables(newTablelist);
		}
		
		
		TemplateUtil.getInstance(projectInfo.getTemplatePath()).build("/maven-project-template/generatorConfig.properties", 
				pathUtil.getJavaResourcePath("dal").getPath()+"mybatis-generator/generatorConfig.properties", projectInfo);
		TemplateUtil.getInstance(projectInfo.getTemplatePath()).build("/maven-project-template/generatorConfig.xml", 
				pathUtil.getJavaResourcePath("dal").getPath()+"mybatis-generator/generatorConfig.xml", projectInfo);
		try {
			build("mvn mybatis-generator:generate",projectInfo.getProjectPath()+"/"+projectInfo.getArtifactId()+"/"+projectInfo.getArtifactId()+"-dal/");
		} catch (Exception e) {
			e.printStackTrace();
		}
		Map<String,String> params = new HashMap<>();
		params.put("groupId", projectInfo.getGroupId());
		for(TableInfo tableInfo : projectInfo.getTables()) {
			if(tableInfo.getTableName().equalsIgnoreCase("sys_short_cut"))
				continue;
			params.put("clazzName", NameUtil.getClassName(tableInfo.getTableName()));
			TemplateUtil.getInstance(projectInfo.getTemplatePath()).build("/maven-project-template/mybatis/MyMapper.java", 
					pathUtil.getDalPackagePath().getPath()+"/mybatis/mymapper/My"+NameUtil.getClassName(tableInfo.getTableName())+"Mapper.java", params,false);
			TemplateUtil.getInstance(projectInfo.getTemplatePath()).build("/maven-project-template/mybatis/MyMapper.xml", 
					pathUtil.getJavaResourcePath("dal").getPath()+"/mybatis/myxml/My"+NameUtil.getClassName(tableInfo.getTableName())+"Mapper.xml", params,false);
			
		}
		ProjectMaker.afterBuild(projectInfo);
	}
	
	public static void makeEnums(ProjectInfo projectInfo) {
		
		List<TableInfo> tables = projectInfo.getTables();
		for(TableInfo table:tables) {
			if(table.getTableName().equalsIgnoreCase("sys_short_cut"))
				continue;
			List<ColumnInfo> columns = table.getColumns();
			Map<String, List<String>> allenums = getEnums(columns);
			StringBuilder sb = new StringBuilder();
			if(allenums.keySet().size() > 0) {
				allenums.forEach((key,list) -> {
					sb.append(key+",");
				});
				System.out.println(table.getTableName()+"找到枚举"+allenums.keySet().size()+"个,"+sb);
			}
			EnumInfo enumInfo = new EnumInfo();
			enumInfo.setTableName(NameUtil.getClassName(NameUtil._2JavaName(table.getTableName())));
			enumInfo.setArtifactId(projectInfo.getArtifactId());
			enumInfo.setCompanyName(projectInfo.getCompanyName());
			allenums.forEach((key,enums) ->{
				enumInfo.setEnumName(StringUtils.capitalize(key));
				enumInfo.setEnumValues(enums);
				TemplateUtil.getInstance(projectInfo.getTemplatePath()).build("/maven-project-template/service/EnumTemplate.java",
						pathUtil.getDalPackagePath().getPath()+"mybatis/enums/"+enumInfo.getTableName()+enumInfo.getEnumName()+"Enum.java"
						, enumInfo);
			});
		}
	}
}
